<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2005/08/07 05:20:29 $)
// $RCSfile: functions_messages.php,v $ : $Revision: 1.3 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Called when no staff is online and user decides to leave a message instead
*/
function clientLeaveMessage($subject, $fullname, $email, $departmentid, $message)
{
	global $dbCore;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."messages` (`dateline`, `replydateline`, `fullname`, `email`, `subject`, `departmentid`, `messagestatus`, `staffid`) VALUES('". DATENOW ."', '". DATENOW ."', '". $dbCore->escape($fullname) ."', '". $dbCore->escape($email) ."', '". $dbCore->escape($subject) ."', '". $dbCore->escape($departmentid) ."', '". MESSAGE_NEW ."', '0');");
		
	$messageid = $dbCore->lastInsertId();
		
	$dbCore->shutdownQuery("INSERT INTO `". TABLE_PREFIX ."messagedata` (`messageid`, `contenttype`, `contents`) VALUES('". $dbCore->escape($messageid) ."', '". CONTENT_CLIENT ."', '". $dbCore->escape($message) ."');");

	rebuildLivesupportCache();
}

/**
* Returns the message ids that are in the current staff's department
*/
function checkStaffMessagePermission($messageidarray)
{
	global $dbCore, $_SWIFT;

	// ======= PERMISSION CHECK =======
	// Get all the departments this staff is assigned to
	$departmentidlist = array();
	$_staffgroupid = $dbCore->escape($_SWIFT["staff"]["staffgroupid"]);
	$dbCore->query("SELECT departments.departmentid FROM `". TABLE_PREFIX ."departments` AS departments LEFT JOIN `". TABLE_PREFIX ."staffassigns` AS staffassigns ON (staffassigns.departmentid = departments.departmentid) LEFT JOIN `". TABLE_PREFIX ."groupassigns` AS groupassigns ON (groupassigns.departmentid = departments.departmentid) WHERE staffassigns.staffid = '". $dbCore->escape($_SWIFT["staff"]["staffid"]) ."' OR groupassigns.staffgroupid = '". iif($_SWIFT["staff"]["groupassigns"]=="1",$_staffgroupid, "0") ."';");
	while ($dbCore->nextRecord())
	{
		$departmentidlist[] = $dbCore->Record["departmentid"];
	}

	// Great now build a department id list of message ids
	$messageidlist = array();
	$dbCore->query("SELECT messageid, departmentid FROM `". TABLE_PREFIX ."messages` WHERE `messageid` IN (". buildIN($messageidarray) .");");
	while ($dbCore->nextRecord())
	{
		if (in_array($dbCore->Record["departmentid"], $departmentidlist))
		{
			$messageidlist[] = $dbCore->Record["messageid"];
		}
	}
	// ======= END PERMISSION CHECK =======

	return $messageidlist;
}

/**
* Deletes a message with given message ids
*/
function deleteMessages($messageidarray)
{
	global $dbCore, $_SWIFT;

	if (!is_array($messageidarray))
	{
		return false;
	} else if (count($messageidarray) == 0) {
		return false;
	}
	
	$messageidarray = checkStaffMessagePermission($messageidarray);

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."messages` WHERE `messageid` IN (". buildIN($messageidarray) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."messagedata` WHERE `messageid` IN (". buildIN($messageidarray) .");");

	rebuildLivesupportCache();

	return true;
}

/**
* Changes the message status for given message ids
*/
function changeMessageStatus($messageidarray, $newstatus)
{
	global $dbCore, $_SWIFT;

	if (!is_array($messageidarray))
	{
		return false;
	} else if (count($messageidarray) == 0) {
		return false;
	}

	$messageidarray = checkStaffMessagePermission($messageidarray);

	$dbCore->query("UPDATE `". TABLE_PREFIX ."messages` SET `messagestatus` = '". $dbCore->escape($newstatus) ."' WHERE `messageid` IN (". buildIN($messageidarray) .");");

	rebuildLivesupportCache();

	return true;
}

/**
* Marks the given message ids as replied
*/
function markMessageAsReplied($messageidarray)
{
	global $dbCore, $_SWIFT;

	if (!is_array($messageidarray))
	{
		return false;
	} else if (count($messageidarray) == 0) {
		return false;
	}
	
	$messageidarray = checkStaffMessagePermission($messageidarray);

	$dbCore->query("UPDATE `". TABLE_PREFIX ."messages` SET `messagestatus` = '". MESSAGE_REPLIED ."', `staffid` = '". $_SWIFT["staff"]["staffid"] ."', `replydateline` = '". DATENOW ."' WHERE `messageid` IN (". buildIN($messageidarray) .");");

	rebuildLivesupportCache();

	return true;
}

/**
* Reply to a given message
*/
function replyToMessage($messageid, $subject, $reply)
{
	global $dbCore, $_SWIFT;

	$_message = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."messages` AS messages LEFT JOIN `". TABLE_PREFIX ."messagedata` AS messagedata ON (messages.messageid = messagedata.messageid) WHERE messages.messageid = '". $dbCore->escape($_REQUEST["messageid"]) ."';");
	if ($_message["messageid"] == "")
	{
		return false;
	}

	// First add the necessary data
	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."messages` SET replydateline = '". DATENOW ."', messagestatus = '". MESSAGE_REPLIED ."', staffid = '". $dbCore->escape($_SWIFT["staff"]["staffid"]) ."' WHERE `messageid` = '". $dbCore->escape($_message["messageid"]) ."';");

	$dbCore->shutdownQuery("INSERT INTO `". TABLE_PREFIX ."messagedata` (`messageid`, `contenttype`, `contents`) VALUES ('". $dbCore->escape($_message["messageid"]) ."', '". CONTENT_STAFF ."', '". $dbCore->escape($reply) ."');");

	// Now send the email
	$mail = new SWIFT_Mail();

	$emailtext = $reply;
	$emailhtml = nl2br($reply);
		
	$mail->setSubject($subject);
	$mail->setData($emailhtml, $emailtext);

	$mail->sendMail($_message["email"], $_SWIFT["staff"]["email"], $_SWIFT["staff"]["fullname"]);

	rebuildLivesupportCache();

	return $_message["email"];
}

/**
* Returns the subject of given message
*/
function getMessageSubject($messageid)
{
	global $dbCore, $_SWIFT;

	if (empty($messageid))
	{
		return false;
	}

	$result = $dbCore->queryFetch("SELECT `subject` FROM `". TABLE_PREFIX ."messages` WHERE `messageid` = '". $dbCore->escape($messageid) ."';");
	return $result["subject"];
}

/**
* Callback for parsing cron logs data
*/
function _messageFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	$record["messages.fullname"] = htmlspecialchars($record["fullname"]);
	$record["messages.subject"] = '<a href="index.php?_m=livesupport&_a=replytomessage&messageid='. $record["messageid"] .'" title="'. $_SWIFT["language"]["reply"] .'">'.htmlspecialchars($record["subject"])."</a>";
	$record["messages.dateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["dateline"]);

	$record["options"] = '<a href="index.php?_m=livesupport&_a=replytomessage&messageid='. $record["messageid"] .'" title="'. $_SWIFT["language"]["reply"] .'"><img src="'. $_SWIFT["themepath"] .'icon_reply.gif" border="0">&nbsp;'. $_SWIFT["language"]["reply"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["actionconfirm"] .'\', \'index.php?_m=livesupport&_a=messages&do=delete&messageid='. $record["messageid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';
	return $record;
}

/**
* Callback for parsing cron logs data
*/
function _messageRepliedFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	$record["messages.fullname"] = htmlspecialchars($record["fullname"]);
	$record["messages.subject"] = '<a href="index.php?_m=livesupport&_a=messagedetails&messageid='. $record["messageid"] .'" title="'. $_SWIFT["language"]["details"] .'">'.htmlspecialchars($record["subject"]).'</a>';
	$record["messages.dateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["dateline"]);
	$record["messages.replydateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["replydateline"]);
	$record["messages.staffid"] = $_SWIFT["staffcache"][$record["staffid"]]["fullname"];

	$record["options"] = '<a href="index.php?_m=livesupport&_a=messagedetails&messageid='. $record["messageid"] .'" title="'. $_SWIFT["language"]["details"] .'"><img src="'. $_SWIFT["themepath"] .'icon_details.gif" border="0">&nbsp;'. $_SWIFT["language"]["details"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["actionconfirm"] .'\', \'index.php?_m=livesupport&_a=messages&do=delete&messageid='. $record["messageid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';
	return $record;
}

/**
* Mass Action: Mark Messages as Replied
*/
function _maMarkRepliedMessage()
{
	global $dbCore, $_SWIFT;

	if (!is_array($_POST["itemid"]))
	{
		return false;
	} else if (count($_POST["itemid"]) == 0) {
		return false;
	}
	
	markMessageAsReplied($_POST["itemid"]);
}

/**
* Mass Action: Delete Given Messages
*/
function _maDeleteMessage()
{
	global $_SWIFT;

	if (!is_array($_POST["itemid"]))
	{
		return false;
	} else if (count($_POST["itemid"]) == 0) {
		return false;
	}

	deleteMessages($_POST["itemid"]);
}

/**
* Rebuilds the live support cache
*/
function rebuildLivesupportCache()
{
	global $dbCore, $_SWIFT, $datastore;

	$livesupportcache = array();
	$dbCore->query("SELECT COUNT(*) AS totalitems, `departmentid` FROM `". TABLE_PREFIX ."messages` WHERE `messagestatus` = '". MESSAGE_NEW ."' GROUP BY `departmentid`;");
	while ($dbCore->nextRecord())
	{
		$livesupportcache["messagecount"][$dbCore->Record["departmentid"]] = $dbCore->Record["totalitems"];		
	}

	$datastore->update("livesupportcache", $livesupportcache);

	return true;
}

?>